<script setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import request from '@/utils/request.js'
import { useUserStore } from '@/stores/index.js'
import { useRouter } from 'vue-router'
const isLogin = ref(true)
const router = useRouter()
const showPassword = ref(true);
const showConfirmPassword = ref(true);
const loginForm = ref({
  student_id: '',
  password: ''
})
const registerForm =ref({
  nickname: '',
  student_id: '',
  password: '',
  confirmPassword: ''
})
const transform = () => {
  isLogin.value = !isLogin.value
}
const register = async () => {
    const student_idRegex = /^\d{12}$/
    const passwordRegex = /^[a-zA-Z0-9]{8,12}$/;
      if(registerForm.value.nickname === ''){
        ElMessage.error('昵称不能为空')
        return;
      }
      if(!student_idRegex.test(registerForm.value.student_id)){
        ElMessage.error('学号应为12位数字')
        return;
      }
      if(!passwordRegex.test(registerForm.value.password)){
        ElMessage.error('密码应为8到12位数字或字母')
        return;
      }
      if(registerForm.value.password !== registerForm.value.confirmPassword){
        ElMessage.error('两次密码输入不一致，请重新输入')
        return;
      }
      try {
        // 发送请求（注意：后端接收的是 student_id，需映射字段名）
        const res = await request.post('/register', {
          nickname: registerForm.value.nickname,
          student_id: registerForm.value.student_id,
          password: registerForm.value.password,
          confirmPassword: registerForm.value.confirmPassword
        });

        // 请求成功（后端返回 status:200，拦截器已处理）
        ElMessage.success(res.message || '注册成功');

        const userStore = useUserStore()

        userStore.setUserId(res.userId)
        // 可添加跳转逻辑，如：router.push('/login');
        router.push({
          path: '/user/finish',
          query: {
            mode: "完善信息"
          }
        });

      } catch (error) {
        // 错误处理（拦截器已显示错误信息，这里可做额外处理）
        console.error('注册失败:', error);
      }
}
const login =async () => {
    const student_idRegex = /^\d{12}$/
    const passwordRegex = /^[a-zA-Z0-9]{8,12}$/;
      if(!student_idRegex.test(loginForm.value.student_id)){
        ElMessage.error('学号应为12位数字')
        return;
      }
      if(!passwordRegex.test(loginForm.value.password)){
        ElMessage.error('密码应为8到12位数字或字母')
        console.log(loginForm.value.password)
        return;
      }
      try {
        const res = await request.post('/login', {
          student_id: loginForm.value.student_id,
          password: loginForm.value.password,
        });
        const userStore = useUserStore()

        userStore.setToken(res.token , res.student_id,res.userId,res.avatar)
        // 请求成功（后端返回 status:200，拦截器已处理）
        ElMessage.success(res.message || '登录成功');
        //跳转到headYes页面
        // window.location.href = '/headYes'
        // 可添加跳转逻辑，如：router.push('/login');
        router.push('/headYes')

      } catch (error) {
        // 错误处理（拦截器已显示错误信息，这里可做额外处理）
        console.error('登录失败:', error);
      }
}

</script>
<template>
  <el-row class="login-container">
    <el-col :span="12" :class="{ 'log-bg-login': isLogin, 'log-bg-register': !isLogin }" ></el-col>
    <el-col v-if="isLogin" :span="8" :offset="2" class="login-form">
      <el-form class="login-form-container">
        <el-form-item>
          <h1 class="login-form-container-title">登录</h1>
        </el-form-item>
        <el-form-item>
          <el-input v-model="loginForm.student_id" prefix-icon="User" placeholder="请输入校园学号" ></el-input>
        </el-form-item>
        <el-form-item>
          <el-input v-model="loginForm.password" prefix-icon="Lock" placeholder="请输入密码" showPassword></el-input>
        </el-form-item>
        <el-form-item>
           <el-button type="primary" round @click="login">
            登录
            </el-button>
        </el-form-item>
         <el-form-item class="login-form-container-set">
          <div class="login-form-container-set-left" @click="transform" >注册-></div>
          <div class="login-form-container-set-right">忘记密码</div>
        </el-form-item>
      </el-form>
    </el-col>
    <el-col v-else :span="8" :offset="2" class="login-form" >
        <el-form class="login-form-container" @submit.prevent="register">
        <el-form-item>
          <h1 class="login-form-container-title">注册</h1>
        </el-form-item>
         <el-form-item>
          <el-input v-model="registerForm.nickname" prefix-icon="User" placeholder="请输入昵称" required ></el-input>
        </el-form-item>
        <el-form-item>
          <el-input v-model="registerForm.student_id" prefix-icon="User" placeholder="请输入校园学号" required ></el-input>
        </el-form-item>
        <el-form-item>
          <el-input v-model="registerForm.password" prefix-icon="Lock" placeholder="请输入密码" show-password :suffix-icon="showPassword ? '隐藏' : '显示'" @click:suffix="showPassword = !showPassword" required></el-input>
        </el-form-item>
        <el-form-item>
          <el-input v-model="registerForm.confirmPassword" prefix-icon="Lock" placeholder="请再次输入密码" show-password :suffix-icon="showPassword ? '隐藏' : '显示'" @click:suffix="showConfirmPassword= !showConfirmPassword" required></el-input>
        </el-form-item>
        <el-form-item>
           <el-button type="primary" round @click="register">
            注册
            </el-button>
        </el-form-item>
         <el-form-item class="login-form-container-set">
          <div class="login-form-container-set-left"  >已有帐号-></div>
          <div class="login-form-container-set-right" @click="transform">登录</div>
        </el-form-item>
      </el-form>
    </el-col>
  </el-row>
</template>
<style>
.login-container{
  display: flex;
  align-items: center;
  height: 100vh;
  background: linear-gradient(to right, #eaf8f5, #f8fdfc);
}
.log-bg-login {
 background-image: url('@/assets/images/login1.png');
  background-size: 100% 100%;
  background-position: center;
  background-repeat: no-repeat;
  height: 100vh;
  border-radius: 0% 7% 7% 0%;
  box-shadow: 0 8px 24px rgba(0,0,0,0.1);
}
.log-bg-register {
  background-image: url('@/assets/images/register.png');
  background-size: 100% 100%;
  background-position: center;
  background-repeat: no-repeat;
  height: 100vh;
  border-radius: 0% 7% 7% 0%;
  box-shadow: 0 8px 24px rgba(0,0,0,0.1);
}
.login-form {
  display: flex;
  flex-direction: column;
  align-items: center;
  background: rgba(255,255,255,0.8);
  backdrop-filter: blur(10px);
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0,0,0,0.05);

}
.login-form-container {
  width: 80%;
}
.login-form-container-title {
  font-size: 28px;
  background: linear-gradient(120deg, #68d3c2, #42b8a3);
  -webkit-background-clip: text;
  background-clip: text;
  color: transparent;
  position: relative;
}

.login-form-container .el-input {
  height: 90%;
  margin-bottom: 15px;
  --el-input-border-color: #d9f2ed; /* 浅绿边框 */
  --el-input-focus-border-color: #87e8de; /* 聚焦时亮绿色 */
  box-shadow: 0 0 12px rgba(135, 232, 222, 0.2); /* 氛围光 */
  transition: all 0.3s ease;
}

.login-form-container .el-input:hover,
.login-form-container .el-input:focus {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(135, 232, 222, 0.3);
}

.login-form-container .el-button {
  width: 100%;
  height: 130%;
  font-size: 20px;
  background: linear-gradient(to right, #68d3c2, #42b8a3);
  border: none;
}

.login-form-container .el-button:hover {
  background: linear-gradient(to right, #58c2b2, #39a898);
}
.login-form-container-set {
  display: flex;
}

.login-form-container-set-left {
  padding-right: 70%;
  cursor: pointer;
}
.login-form-container-set-right {
  color: #1bac55;
  cursor: pointer;
}
</style>
